package com.atguigu.tingshu.search.listener;


import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.search.service.MqOpsService;
import com.atguigu.tingshu.search.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class SearchInfoListener {


    @Autowired
    private MqOpsService mqOpsService;

    @SneakyThrows
    @RabbitListener(bindings = {@QueueBinding(value =
            @Queue(value = MqConst.QUEUE_ALBUM_UPPER,durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM,durable = "true"),
            key ={MqConst.ROUTING_ALBUM_UPPER}
            )})
    public void albumOnSale(String content, Message message, Channel channel){
        log.info("下游搜索微服务接收到上游专辑微服务的用户消息{},并完成专辑上架操作",content);
        //1.判断下游消费者是否获取到了消息
        if (StringUtils.isEmpty(content)){
            return; //不用消费了
        }
        //2.获取消息(未来对获取的消息进行消息解析)
        Long albumId =Long.parseLong(content);
        //3.消费消息
        int count= mqOpsService.albumOnSale(albumId);
        log.info("上架专辑:{},",count>0?"成功":"失败");


        //4.手动应答
        //4.1获取消息的唯一标识
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag,false); //一条一条手动确认,不是批量确认
    }
    @SneakyThrows
    @RabbitListener(bindings = {@QueueBinding(value =
    @Queue(value = MqConst.QUEUE_ALBUM_LOWER,durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM,durable = "true"),
            key ={MqConst.ROUTING_ALBUM_LOWER}
    )})
    public void albumOffSale(String content, Message message, Channel channel){
        log.info("下游搜索微服务接收到上游专辑微服务的用户消息{},并完成专辑下架操作",content);
        //1.判断下游消费者是否获取到了消息
        if (StringUtils.isEmpty(content)){
            return; //不用消费了
        }
        //2.获取消息(未来对获取的消息进行消息解析)
        Long albumId =Long.parseLong(content);
        //3.消费消息
        int count= mqOpsService.albumOffSale(albumId);
        log.info("上架专辑:{},",count>0?"成功":"失败");


        //4.手动应答
        //4.1获取消息的唯一标识
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag,false); //一条一条手动确认,不是批量确认
    }


}
